package com.jerry.usbserial.fragment.udp

import android.Manifest
import android.app.AlertDialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.location.LocationManager
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.core.location.LocationManagerCompat
import com.jerry.usbserial.fragment.BaseFragment
import com.jerry.usbserial.util.toIP
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.OnPermissionDenied
import permissions.dispatcher.RuntimePermissions


/**
 * Created by dugang on 2020/7/7.
 */
@RuntimePermissions
abstract class UdpFragment : BaseFragment() {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        requestPermissionWithPermissionCheck()
    }

    override fun onResume() {
        super.onResume()
        val filter = IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION)
        }
        mContext.registerReceiver(mReceiver, filter)
    }


    override fun onPause() {
        super.onPause()
        mContext.unregisterReceiver(mReceiver)
    }


    @NeedsPermission(Manifest.permission.ACCESS_FINE_LOCATION)
    fun requestPermission() {
        onWifiChanged()
    }

    @OnPermissionDenied(Manifest.permission.ACCESS_FINE_LOCATION)
    fun permissionDenied() {
        AlertDialog.Builder(mContext)
            .setTitle("提示")
            .setMessage("在 Android M及以上版本，如果您禁止授权位置权限，APP将无法获取 Wi-Fi 信息")
            .setCancelable(false)
            .setPositiveButton(android.R.string.ok, null)
            .show()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)
    }

    private fun onWifiChanged() {
        val locationManager = mContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (!LocationManagerCompat.isLocationEnabled(locationManager)) {
            handlerResult(error = "请打开 GPS 以获取 Wi-Fi 信息")
            return
        }
        val wifiManager = mContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val wifiInfo = wifiManager.connectionInfo
        if (wifiInfo.networkId == -1 || wifiInfo.ssid == "<unknown ssid>") {
            handlerResult(error = "请先连接 Wi-Fi")

            return
        }
//        if (wifiInfo.frequency in 4901..5899) {
//            handlerResult(error = "当前连接的是 5G Wi-Fi, 设备仅支持 2.4G Wi-Fi")
//            return
//        }
        val ssid = wifiInfo.ssid.replace("\"", "")
        val bssid = wifiInfo.bssid
        val ip = wifiInfo.ipAddress.toIP()

        handlerResult(ssid = ssid, bssid = bssid, ip = ip)
    }

    abstract fun handlerResult(ssid: String? = null, bssid: String? = null, ip: String? = null, error: String? = null)

    private val mReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            if (intent.action == WifiManager.NETWORK_STATE_CHANGED_ACTION || intent.action == LocationManager.PROVIDERS_CHANGED_ACTION) {
                onWifiChanged()
            }
        }
    }
}